package org.fjsei.yewu.job.jobs;

import org.fjsei.yewu.job.repository.SplJob;
import org.fjsei.yewu.job.repository.SplJobRepository;
import org.fjsei.yewu.job.service.SplitTask;
import org.fjsei.yewu.job.util.Constant;
import jakarta.persistence.EntityManager;
import jakarta.persistence.PersistenceContext;
import lombok.extern.slf4j.Slf4j;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import java.util.Date;

//原本的 implements Job
@Slf4j
@DisallowConcurrentExecution //Result: is_nonconcurrent = 1 in the qrtz_fired_triggers table. Quartz ensures that only one instance of MyNonConcurrentJob runs at a time
@Component        //不加上 @Component 运行是可以，IDEA爆红的。
//@Transactional
public class CreditCardJob implements InterruptableJob {
    private volatile boolean interrupted = false; // 中断标志
    private JobKey jobKey;      // Job 的唯一标识
//    @PersistenceContext
//    private EntityManager entityManager;                //EntityManager相当于hibernate.Session：
    @Autowired
    protected SplJobRepository splJobRepository;
    @Autowired
    protected SplitTask splitTask;

//不能加public CreditCardJob(SplitTask splitTask){}报错 Caused by: java.lang.NoSuchMethodException: org.fjsei.yewu.job.jobs.CreditCardJob.<init>()
//    public CreditCardJob(SplitTask splitTask) {
//        this.splitTask = splitTask;
//    }

    //jakarta.persistence.TransactionRequiredException: No EntityManager with actual transaction available for current thread - cannot reliably process 'joinTransaction' call]

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        jobKey = jobExecutionContext.getJobDetail().getKey();
        SplJob splJob= splJobRepository.findByGroupNameAndJobName(jobKey.getGroup(),jobKey.getName());
//        if(!entityManager.isJoinedToTransaction()) entityManager.joinTransaction();
//        Assert.isTrue(entityManager.isJoinedToTransaction(),"没emFjtj Transaction");
        long startDate = System.currentTimeMillis();
        log.info("Job with JobName {}, GroupName {} is started at {}", jobExecutionContext.getJobDetail().getKey().getName(), jobExecutionContext.getJobDetail().getKey().getGroup(), Constant.SIMPLE_DATE_FORMAT.format(new Date()));
        try {
            // 模拟长时间运行的任务
            for(int i=0; i<=90; i++){
                if (interrupted) {
                    System.out.println("Job 被中断...");
                    return; // 停止任务执行
                }
                log.info("Counter {}", i);
                Thread.sleep(3100); // Job takes 30 second to complete
            }
//            splJob.setOffs(330577L);
            splJob=commitSplit79(jobKey);
//            splitTask.commitSplit5(jobKey);
//            splJobRepository.save(splJob);
        } catch (InterruptedException e) {
            // 处理线程中断异常
            Thread.currentThread().interrupt();  // 恢复中断状态
            System.out.println("线程被中断...");
        } finally {
            log.info("Job 执行完成或运行过程被中断也算完毕的JobName {}, GroupName {} is completed at {} and time taken is {} second",
                    jobExecutionContext.getJobDetail().getKey().getName(), jobExecutionContext.getJobDetail().getKey().getGroup(),
                    Constant.SIMPLE_DATE_FORMAT.format(new Date()), (System.currentTimeMillis() - startDate) / 1000);
        }
    }

    @Transactional
    public SplJob commitSplit79(JobKey jobKey) {
//        if(!entityManager.isJoinedToTransaction())      entityManager.joinTransaction();
//        Assert.isTrue(entityManager.isJoinedToTransaction(),"没emFjtj Transaction");
        SplJob splJob= splJobRepository.findByGroupNameAndJobName(jobKey.getGroup(),jobKey.getName());
        splJob.setOffs(918771L);
        return splJobRepository.save(splJob);
    }

    @Override
    public void interrupt() throws UnableToInterruptJobException {
        interrupted = true; // 设置中断标志为 true
        log.info("Job with JobName {}, GroupName {} is started at {}", jobKey.getName(), jobKey.getGroup(), Constant.SIMPLE_DATE_FORMAT.format(new Date()));
    }
}
